﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Windows.Forms;

namespace skald_db
{
    public class User
    {
        private string Username;
        public string Name
        {
            get { return Username; }
        }
        private string Password;
        private int Rights;
        public User(string inUsername, string inPassword, int inRights)
        {
            this.Username = inUsername;
            this.Password = inPassword;
            this.Rights = inRights;
        }
        public bool isUserExists(string inUsername, string inPassword)
        {
            bool res = false;
            bool checkPassword = false;

            if ((inUsername == this.Username) && (inPassword == this.Password))
            {
                res = true;
            }
            return res;
        }
        public int GetRights
        {
            get { return this.Rights; }
        }
    }
    class Authorisation
    {
        /* Здесь будет манипуляция с файлом пользователей
         * Так то план такой
         * 1 - Админ
         * 2 - Маваши
         * 3 - Петух
         */
        //
        private User[] Users; // Массив петухов
        int cntUsers = 0; // Количество петухов
        public string[] GetUsers()
        {
            string[] str = new string[Users.Length];
            for (int i = 0; i < Users.Length; i++)
            {
                str[i] = Users[i].Name;
            }
            return str;
        }
        public Authorisation()
        {
            try
            {
                using (StreamReader inUsers = File.OpenText(@"cfg\users.info"))
                {
                    string s = "";
                    while ((s = inUsers.ReadLine()) != null)
                    {
                        cntUsers++;
                    }
                }
                Users = new User[cntUsers];
                using (StreamReader inUsers = File.OpenText(@"cfg\users.info"))
                {
                    for (int i = 0; i < cntUsers; i++)
                    {
                        string Info = inUsers.ReadLine();
                        string[] parsedInfo = Info.Split(' ');
                        int parsedRights = Int32.Parse(parsedInfo[2]);
                        Users[i] = new User(parsedInfo[0], parsedInfo[1], parsedRights);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public bool DeleteUser(string inName)
        {
            bool res = false;
            int num = -1;
            for (int i = 0; i < Users.Length; i++)
            {
                if (inName == Users[i].Name)
                {
                    num = i;
                }
            }
            if (num == -1)
            {
                return false;
            }
            string output = "";
            try
            {
                using (StreamReader sr = File.OpenText(@"cfg\users.info"))
                {
                    for (int i = 0; i < Users.Length; i++)
                    {
                        if (i == num)
                        {
                            sr.ReadLine();
                        }
                        else
                        {
                            output += sr.ReadToEnd();
                        }
                    }
                }
                File.WriteAllText(@"cfg\users.info", output);
                res = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                res = false;
            }
            return res;
        }
        public bool AddUser(string inName, string inPassword, int inRights)
        {
            bool res = false;
            string output = "";
            try
            {
                using (StreamReader sr = File.OpenText(@"cfg\users.info"))
                {
                    output += sr.ReadToEnd();
                }
                string md5Password;
                using (MD5 md5Hash = MD5.Create())
                {
                    md5Password = GetMd5Hash(md5Hash, inPassword);
                }
                output += "\n" + inName + " " + md5Password + " " + inRights;
                Console.WriteLine(output);
                File.WriteAllText(@"cfg\users.info", output);
                res = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                res = false;
            }
            return res;
        }
        private string GetMd5Hash(MD5 md5Hash, string input)
        {
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
        // Возвращает id прав юзера если ОК, если нет - 0
        public int CheckUser(string inUsername, string inPassword)
        {
            int res = 0;
            string md5Password;
            using (MD5 md5Hash = MD5.Create())
            {
                md5Password = GetMd5Hash(md5Hash, inPassword);
            }
            if (Users == null) { MessageBox.Show(" Не иництализированн объект файла"); Application.Exit(); return 0; }
            foreach (User u in Users)
            {
                if (u.isUserExists(inUsername, md5Password))
                {
                    res = u.GetRights;
                }
            }
            return res;
        }
    }
}
